package com.ruoyi.quartz.task;

import com.ruoyi.slope.video.camera.domain.SlopeCamera;
import com.ruoyi.slope.video.camera.service.impl.SlopeCameraServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Component("GetCameraUrl")
public class GetCameraUrl {

    @Autowired
    SlopeCameraServiceImpl slopeCameraServiceImpl;

    private static final String API_URL = "https://open.ys7.com/api/lapp/v2/live/address/get";
    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();
    public void getUrl(){
        updateAllCameraVideoUrls();
    }

    public void updateAllCameraVideoUrls() {
        List<SlopeCamera> cameraList = slopeCameraServiceImpl.selectSlopeAllCamera();

        for (SlopeCamera camera : cameraList) {
            String deviceId = camera.getCameraCode();

            fetchVideoUrlAndUpdate(camera);
            slopeCameraServiceImpl.updateSlopeCamera(camera); // 更新数据库记录
        }
    }

    public String fetchToken(){
        String urlWithParams = "https://open.ys7.com/api/lapp/token/get?appKey=33fbe49312e24bb4b0b0fe0c65402e78&appSecret=112acee14c43707ecd9413cb6e8514b6";
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<String> requestEntity = new HttpEntity<>("", headers);

            ResponseEntity<String> response = restTemplate.exchange(
                    urlWithParams,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            JsonNode jsonNode = objectMapper.readTree(response.getBody());

            String code = jsonNode.path("code").asText();
            String msg = jsonNode.path("msg").asText();

            if ("200".equals(code)) {
                return jsonNode.path("data").path("accessToken").asText();
            } else {
                String errorInfo = String.format("错误代码：%s，信息：%s", code, msg);
                System.err.println("视频链接获取失败，" + errorInfo);
            }
        } catch (Exception e) {
            System.err.println("请求异常: " + e.getMessage());
        }
        return null;
    }

    public void fetchVideoUrlAndUpdate(SlopeCamera camera) {
        if (camera.getCameraCode() == null || camera.getCameraCode().trim().isEmpty()) {
            System.out.println("摄像头编号未填写");
            return;
        }
        String token = fetchToken();
        if  (token == null) {
            return;
        }
        String urlWithParams = API_URL + "?accessToken=" + token + "&deviceSerial=" + camera.getCameraCode();

        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<String> requestEntity = new HttpEntity<>("", headers);

            ResponseEntity<String> response = restTemplate.exchange(
                    urlWithParams,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            JsonNode jsonNode = objectMapper.readTree(response.getBody());

            String code = jsonNode.path("code").asText();
            String msg = jsonNode.path("msg").asText();

            if ("200".equals(code)) {
                String videoUrl = jsonNode.path("data").path("url").asText();
                videoUrl = "https://open.ys7.com/console/jssdk/pc.html?accessToken="+token+"&url="+videoUrl;
                camera.setVideoUrl(videoUrl);
                camera.setCameraStatus("在线");
                System.out.println("视频链接获取成功: " + videoUrl);
            } else {
                String errorInfo = String.format("错误代码：%s，信息：%s", code, msg);
                camera.setCameraStatus("离线");
                camera.setVideoUrl(errorInfo); // 设置错误信息到 videoUrl 字段中
                System.err.println("视频链接获取失败，" + errorInfo);
            }
        } catch (Exception e) {
            camera.setCameraStatus("离线");
            camera.setVideoUrl("");
            System.err.println("请求异常: " + e.getMessage());
        }
    }

}
